<template>
<el-card class="card_box">
    <div class="basic-flex padding-bottom-10">
      <div class="card_title">数据概览</div>
      <div class="align-center"><el-button link type="primary" @click="goTo('/users/usersAnalyse')">查看更多 》</el-button></div>
    </div>
    <div >
      <user-statistic :dataObj="list"></user-statistic>
    </div>
 </el-card>
 <el-card>
   <div class="basic-flex">
      <div class="card_title align-center">列表展示</div>
      <div class="search" @click="showMoreSearch=true">
         <img :src="getAssetsFile('images/users/search.svg')" style="padding-right:7px" />   
         <el-link style="color: #ffffff;">高级查询</el-link> 
      </div>
   </div>
   <el-divider></el-divider>
   <el-table :data="userList" border :header-cell-style="tableHeader" style="width: 100%" v-loading="loadingTable">
      <el-table-column type="index" label="序号" min-width="36" align="center"></el-table-column>
      <el-table-column label="用户编号" property="user_id" align="center"></el-table-column>
      <el-table-column label="用户信息" header-align="center" min-width="170">
         <template #default="scope">
            <div >
               <div class="font-medium flex">
                  <div style="width: 40%;"><el-link @click="checkDetail({id:scope.row.user_id,type:scope.row.user_type,url:`/user/userInfo`})" type="primary">{{ scope.row.user_name || '未实名用户' }}</el-link></div>
                  <el-link :underline="false"><img  @click="checkDetail({id:scope.row.user_id,type:scope.row.user_type,url:`/paymentHistory`})" :src="scope.row.user_type=='个人用户'?getAssetsFile('images/users/userIcon.svg'):getAssetsFile('images/users/vipUserIcon.svg')"/></el-link>
               </div>
               <div><text style="width: 70px; display: inline-block;text-align: justify;text-align-last: justify;"> 电话：</text>{{scope.row.user_phone}}</div> 
               <div>身份证号：{{idCard(scope.row.id_card)}}</div> 
            </div>
         </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" width="110">
         <template #default="scope">
            <div> {{ formatTime(scope.row.register_time) }}</div>
            <div :style="status({id:scope.row.id_card,name:scope.row.user_name}).style"> {{ status({id:scope.row.id_card,name:scope.row.user_name}).text }}</div>  
         </template>
      </el-table-column>
      <el-table-column label="缴费" header-align="center" width="220">
         <template #default="scope">
            <div v-if="showData(status({id:scope.row.id_card,name:scope.row.user_name}))" >
                  <div> 套餐金额：{{ scope.row.order_meal_price}}</div>
                  <div> 优惠金额：<el-link :underline="false" type="primary">{{ scope.row.order_gift_price}}</el-link></div>
                  <div> 实付金额：{{ scope.row.order_pay_price}}</div>
               
            </div>
            <div v-else> {{noData}}</div>
         </template>
      </el-table-column>
      <el-table-column label="天数" header-align="center">
         <template #default="scope">
            <div v-if="showData(status({id:scope.row.id_card,name:scope.row.user_name}))">
               <div> 购买天数：{{ scope.row.total_purchase_days}}</div>
               <div> 赠送天数：{{ scope.row.total_gift_days}} </div>
               <div> 使用天数：{{ scope.row.total_usage_days}}</div>
            </div>
            <div v-else> {{ noData }}</div>
         </template>
      </el-table-column>
      <el-table-column label="换电次数" header-align="center">
         <template #default="scope">
            <div v-if="showData(status({id:scope.row.id_card,name:scope.row.user_name}))">
               <div> 累计次数：{{ scope.row.change_battery_total_count}}</div>
               <div> 上月次数：{{ scope.row.change_battery_last_month_count}}</div>
               <div> 本月次数：{{ scope.row.change_battery_current_month_count}}</div>
            </div>
            <div v-else> {{noData}}</div>
         </template>
      </el-table-column>
      <el-table-column label="电量" header-align="center">
         <template #default="scope">
            <div v-if="showData(status({id:scope.row.id_card,name:scope.row.user_name}))">
                  <div> 累计电量：{{ scope.row.all_use_electricity}}</div>
                  <div> 上月电量：{{ scope.row.pre_month_use_electricity}}</div>
                  <div> 本月电量：{{ scope.row.now_month_use_electricity}}</div>
            </div>
            <div v-else> {{noData}}</div>
         </template>
      </el-table-column>
      <el-table-column label="首次取电" align="center" min-width="120">
         <template #default="scope">
            <div v-if="scope.row.first_br_battery_time">
               <div> {{ formatTime(scope.row.first_br_battery_time)}}</div>
               <div> {{ scope.row.first_br_battery_area}}</div>
            </div>
            <div v-else> {{noData}}</div>
         </template>
      </el-table-column>
   </el-table>
   <div class="padding-top-14">
        <el-pagination v-model:current-page="postData.page"
            :total="totalNum"
            v-model:page-size="postData.size"
         :pager-count="7"
         :page-sizes="[5,10, 20]"
         layout="->, total, prev, pager, next,sizes"
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         background>
         </el-pagination>
   </div>
      <el-dialog v-model="showMoreSearch" width="80%">
         <template #header>
            <div class="title font-medium"> 高级查询</div>
            <el-divider></el-divider>
            <div>
               <custom-form :list="formList" :gutter="40" colStyle="padding-top:10px;padding-bottom:10px"></custom-form>
            <div style="width: 100%;text-align: center;padding-top: 40px;">
               <el-button @click="reload" type="info" :icon="RefreshRight" plain> 重置</el-button>
              <el-button @click="search" :icon="Search" type="primary">查询</el-button>
            </div>
         </div>
         </template>
      </el-dialog>             
 </el-card>
</template>
<script setup lang="ts">
import "@/style/modules/users.scss";
import userStatistic from "@/views/users/components/userStaistic/index.vue";
import {getAssetsFile} from "@/utils";
import { RefreshRight, Search} from '@element-plus/icons-vue';
import { dayjs } from "element-plus";
import customForm from "@/views/users/components/customForm/index.vue";
import {userInfoListPath,allUserPath} from "@/config/paths";
import {tableHeader,keyName,idCard} from '@/utils/users/pubConfig'
import {goTo} from "@/utils/users/pubFun"
import router from "@/router";
import type {CusForm} from '@/utils/users/pubConfig';
   const noData=ref<string>('-')
   const showMoreSearch=ref<boolean>(false)
   const showData=computed(()=>{
      return (status:{text:string,style:string})=>{
         if(status.text =='未实名'){
            return false
         }
         return true
      }
   })
   interface GrowthData{
      all_members:number,
      new_members:number,
      all_vip_to_user:number,
      new_orders:number,
      new_rent_batteries:number,
      all_change_batteries:number,
      all_sales:number,
      month_sales:{x_value:string,y_value:number}[]
   }
   interface User{
      all_use_electricity:number,
      change_battery_current_month_count:number,
      change_battery_last_month_count:number,
      change_battery_total_count:number,
      first_br_battery_area?:string,
      first_br_battery_time ?:string,
      id_card?:string,
      now_month_use_electricity:number,
      order_gift_price:number,
      order_meal_price:number,
      order_pay_price:number,
      pre_month_use_electricity:number,
      register_time:string,
      total_gift_days:number,
      total_purchase_days:number,
      total_usage_days:number,
      user_id:number,
      user_name?:string,
      user_phone?:string,
      user_type :string
   }
   interface PostData{
      page:number,
      size:number,
      user_name ?:string,
      user_phone ?:string,
      user_idcard ?:string,
      total_payment ?:Array<number|string>,
      exchange_count ?:Array<number|string>,
      register_time ?:string[],
      user_type ?:string,
      user_status ?:string,
      use_electricity ?:Array<number|string>
   }
   const status=computed(()=>{
      return ({id,name}:{id:string,name:string})=>{
         if(!id && !name){
            return {style:'color:#EC352A',text:'未实名'}
         }
         if(name.indexOf('已注销')!= -1 ){
            return {style:'color:#333333',text:'已注销'}
         }
         return {style:'',text:'已实名'}
      }
   })
   const loadingTable=ref<boolean>(false)
   const postData=ref<PostData>({page:1,size:5})
   const userList=ref<User[]>([{
      all_use_electricity: 0,
      change_battery_current_month_count: 0,
      change_battery_last_month_count: 0,
      change_battery_total_count: 0,
      now_month_use_electricity: 0,
      order_gift_price: 0,
      order_meal_price: 0,
      order_pay_price: 0,
      pre_month_use_electricity: 0,
      register_time: '',
      total_gift_days: 0,
      total_purchase_days: 0,
      total_usage_days: 0,
      user_id: 0,
      user_type: "个人用户"
   }])
   const totalNum=ref<number>(0)
   const formList=ref<CusForm[]>([{
      title:'用户姓名',sm:8,md:8,lg:8,xl:8,showInput:true,inputName:'',value:'user_name',inputPlaceholder:'请输入用户姓名查找'
   },{
      title:'手机号',sm:8,md:8,lg:8,xl:8,showInput:true,inputName:'',labelWidth:'68',value:'user_phone',inputPlaceholder:'请输入11位手机号查找'
   },{
      title:'身份证号',sm:8,md:8,lg:8,xl:8,showInput:true,inputName:'',value:'user_idcard',inputPlaceholder:'请输入身份证号查找'
   },{
      title:'累计缴费',sm:8,md:8,lg:8,xl:8,showSelect:true,showInput:true,style:'display:flex;',value:'total_payment',selectStyle:'margin-right:2%',selectList:[{label:'大于',value:'>'},{label:'等于',value:'='},{label:'小于',value:'<'}],inputPlaceholder:'请输入',suffixTitle:'元',selected:'>'
   },{
      title:'换电次数',sm:8,md:8,lg:8,xl:8,showSelect:true,showInput:true,style:'display:flex',value:'exchange_count',selectStyle:'margin-right:2%',selectList:[{label:'大于',value:'>'},{label:'等于',value:'='},{label:'小于',value:'<'}],inputPlaceholder:'请输入',suffixTitle:'次',selected:'>'
   },{
      title:'注册时间',sm:8,md:8,lg:8,xl:8,showDatePicker:true,date:'',value:'register_time',datePickerStyle:'width:100% '
   },{
      title:'用户类型',sm:8,md:8,lg:8,xl:8,showSelect:true,selected:'',value:'user_type',selectStyle:"width:100% ",selectList:[{label:'个人',value:'个人'},{label:'企业',value:'企业'}]
   },{
      title:'状态',sm:8,md:8,lg:8,xl:8,showSelect:true,selected:'',labelWidth:'68',value:'user_status',selectStyle:"width:100%",selectList:[{label:'未实名',value:'未实名'},{label:'已实名',value:'已实名'},{label:'已注销',value:'已注销'}]
   },{
      title:'使用电量',sm:8,md:8,lg:8,xl:8,showSelect:true,showInput:true,selected:'',value:'use_electricity',inputName:'',style:'display:flex',selectStyle:'margin-right:2%',selectList:[{label:'大于',value:'>'},{label:'等于',value:'='},{label:'小于',value:'<'}],inputPlaceholder:'请输入电量',selected:'>'
   }])
   const formatTime=computed(()=>{
      return (value:string)=>{
         if(!value){
            return ''
         }
         return dayjs(value).format(`YYYY-MM-DD HH:mm:ss`)
      }
   })
   const growthData=ref<GrowthData>({all_members:0,
      new_members:0,
      all_vip_to_user:0,
      new_orders:0,
      new_rent_batteries:0,
      all_change_batteries:0,
      all_sales:0,
      month_sales:[{x_value:'',y_value:0}]})
   onMounted(async()=>{
      const {data} = await baseRequest.get(allUserPath.value)
      growthData.value=data
      userList.value=[]
      const {list,total}=await getUserList()
      userList.value=list
      totalNum.value=total

   })

   //排序
   const list=computed(()=>{
      let newList:any=[]
      for(let [key,value] of Object.entries(growthData.value)){
         if(isNaN(value)) continue
         newList.push({title:keyName[key],value,span:3})
      }
      newList.sort((first,second)=>{
         if(first.title>second.title){
               return 1
         }
         if(first.title<second.title){
               return -1
         }
         return 0
      })
      //1，3，0，5，4，6，2
      return [newList[1],newList[3],newList[0],newList[5],newList[4],newList[6],newList[2]]
   })
   //重置
   function reload(){
      location.reload()
   }
  
   async function getUserList(){
      loadingTable.value=true
      const  {data:{total,user_infos}}=await baseRequest.post(userInfoListPath.value,postData.value)
      loadingTable.value=false
      return {list:user_infos,total} || {list:[],total:0}
   }
   async function search(){
      // console.log('search')
      showMoreSearch.value=false
      postData.value.page=1
      formList.value.forEach(element => {
         const {value:newValue,inputName,showInput,showSelect,showDatePicker,selected,date}=element
         // console.log('input',inputName)
         //单个输入- 用户姓名，手机号，身份证号
         if((showInput&&!showSelect)&&inputName){
            postData.value[newValue]=inputName
         }
         //有单选并有输入的情况-累计缴费，换电次数，使用电量
         else if((showInput && showSelect )&&inputName){
            postData.value[newValue]=[selected,Number(inputName)]
         }
         //单选情况-用户类型，状态
         else if((!showInput && showSelect )&&selected){
            postData.value[newValue]=selected
         }
         //日期选择
         else if(showDatePicker && date.length){
            // console.log('date',date)
            const sTime=dayjs(new Date(date[0])).startOf('date').format(`YYYY-MM-DD HH:mm:ss`)
            const eTime=dayjs(new Date(date[1])).endOf('date').format(`YYYY-MM-DD HH:mm:ss`)
            postData.value[newValue]=[sTime,eTime]
         }
         else{
            delete( postData.value[newValue])
         }
      });
      // console.log('postData',postData.value)
      const {list,total}=await getUserList()
      userList.value=list
      totalNum.value=total
      sessionStorage.setItem('userIndexPost',JSON.stringify(postData.value))
   }
   async function handleSizeChange(val:number){
      postData.value.size=val
      postData.value.page=1
      const {list}=await  getUserList()
      userList.value=list
   }
   async function handleCurrentChange(val:number) {
      postData.value.page=val
      const {list}=await getUserList()
      userList.value=list
   }
   function checkDetail({id,type,url}:{id:string,type:string,url:string}){
      router.push({path:url,query: {id,type}})
   }
   
</script>
<style lang="scss" scoped>
@mixin tab-style{
   border: 1px solid #366EF4;
   border-radius: 2px;
   padding:5px 17px 4px 17px
}
.search{
   color:#FFFFFF;
   background-color: #366EF4;
   @include tab-style
}
.coupon{
   color:#366EF4;
   @include tab-style
}

</style>